package p.ithorns.sample.office.pdf;

import org.htmlunit.BrowserVersion;
import org.htmlunit.NicelyResynchronizingAjaxController;
import org.htmlunit.WebClient;
import org.htmlunit.WebClientOptions;
import org.htmlunit.html.HtmlElement;
import org.htmlunit.html.HtmlPage;
import org.htmlunit.util.Cookie;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.util.Set;

/**
 * TestHtmlUnit
 *
 * @author HtL
 * @date 2025/3/10 11:36
 * @since 1.0.0
 */
public class TestHtmlUnit {

    public static void main(String[] args) throws Exception {
        String url = "http://10.20.32.60:7200/spw-app/special-work/ticket-apply/ticket-record/185?tab=2";
        try {
            testHtmlUnit(url);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }


    static void testHtmlUnit(String url) {
        // 创建一个模拟 Chrome 浏览器的 WebClient 实例
        final WebClient webClient = new WebClient(BrowserVersion.CHROME);
        WebClientOptions options = webClient.getOptions();

        // 配置 WebClient
        //当JS执行出错的时候是否抛出异常
        options.setThrowExceptionOnScriptError(true);
        // 当HTTP的状态非200时是否抛出异常
        options.setThrowExceptionOnFailingStatusCode(true);
        // options.setActiveXNative(false);
        // 是否启用CSS
        options.setCssEnabled(true);
        // 很重要，启用JS
        options.setJavaScriptEnabled(true);
        options.setTimeout(10000);
        //很重要，设置支持AJAX
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());

        webClient.addRequestHeader("Authorization",
                "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiI2ODk2NjE2NjE4NTE1OTY5ODc5Iiwicm5TdHIiOiIzYjM3ZVZUR0Jjb1dxUXBLMUFzcGtwMkFCbVc1R3pjbSJ9.xeZm2EVbdYaUXhhVTtu85dJmN_40ctZANr0MvFBegzk");

        HtmlPage page = null;
        try {
            // 访问百度主页
            page = webClient.getPage(url);
            webClient.waitForBackgroundJavaScript(30000);
            String xml = page.asXml();
            Document parse = Jsoup.parse(xml);
            HtmlElement doc = page.getDocumentElement();

            // 获取并打印 cookies
            Set<Cookie> cookies = webClient.getCookieManager().getCookies();
            System.out.println("Cookies:");
            for (org.htmlunit.util.Cookie cookie : cookies) {
                System.out.println("Name: " + cookie.getName() + ", Value: " + cookie.getValue());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            webClient.close();
        }
    }

}